package com.zyzy.leftfourdead.helper;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import java.util.List;

/**
 * Created by Administrator on 2016/7/21.
 */
public class FragmentHelper {
    /**
     * 替换碎片,替换时原碎片销毁
     * @param manager
     * @param fragmentList
     * @param tabIndex
     * @param layoutId
     */
    public static void replaceFragment(FragmentManager manager, List<Fragment> fragmentList, int tabIndex,
                                       int layoutId) {
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(layoutId, fragmentList.get(tabIndex));
        transaction.commit();
    }

    /**
     * 通过hide(),show()方法选择碎片展示,也就是不在切换时销毁碎片
     * @param manager
     * @param fragmentList
     * @param tabIndex
     * @param layoutId
     */
    public static void switchFragment(FragmentManager manager, List<Fragment> fragmentList, int tabIndex,
                                      int layoutId){
        FragmentTransaction transaction = manager.beginTransaction();

        for(int i = 0;i < fragmentList.size();i++){
            if(fragmentList.get(i).isVisible()){
                transaction.hide(fragmentList.get(i));
            }
        }

        Fragment toFragment = fragmentList.get(tabIndex);
        if(toFragment.isAdded()){
            transaction.show(toFragment);
        }else{
            transaction.add(layoutId,toFragment);
        }
        transaction.commit();
    }
}
